package com.cambright.lotusroot
{
	import com.cambright.Enumerator;

	public class Widget
	{
		private var _componentVec:Vector.<Component> = new Vector.<Component>();
		private var _componentEnumerator:Enumerator = new Enumerator(_componentVec);
		private var _key:WidgetKey;
		
		internal function $invoke():void 
		{ 
			_componentEnumerator.release();
			invoke();
		}
		
		private function $dispose():void 
		{ 
			enabled = false; 
			dispose(); 
			_componentEnumerator.dispose();
			_componentEnumerator = null;
			_componentVec = null;
		}
		
		private var _enabled:Boolean = false;
		final public function get enabled():Boolean
		{
			return _enabled;
		}
		final public function set enabled(value:Boolean):void
		{
			if(_enabled == value) return;
			_enabled = value;
			
			_enabled ? enable() : disable();
		}
		
		internal function $update():void
		{
			if(_enabled)
				update();
			
			_componentEnumerator.capture();
			while(_componentEnumerator.next())
				(_componentEnumerator.current as Component).$update();
			_componentEnumerator.release();
		}
		
		public function get numComponents():int
		{
			return _componentVec.length;
		}
		
		public function get key():Object
		{
			return _key;
		}
		internal function setKey(key:WidgetKey):void
		{
			_key = key;
		}
		
		public function addComponent(definition:Class):*
		{
			var component:Component = new definition();
			_componentVec.push(component);
			component.$invoke();
			return component;
		}
		
		public function removeComponent(component:Component):void
		{
			var index:int = _componentVec.indexOf(component);
			component.enabled = false;
			component.$dispose();
			_componentVec.removeAt(index);
		}
		
		protected function invoke():void {}
		protected function enable():void {}
		protected function disable():void {}
		protected function update():void {}
		protected function dispose():void {}
	}
}